package com.qingchunlin.blogsystem.service;

import com.qingchunlin.blogsystem.common.utils.JWTUtils;
import com.qingchunlin.blogsystem.entity.Result;
import com.qingchunlin.blogsystem.entity.User;
import com.qingchunlin.blogsystem.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User getUserByName(String userName) {
        return userMapper.getUserByName(userName);
    }

    public User getUserById(Integer userId) {
        return userMapper.getUserById(userId);
    }

    public User getAuthorByBlogId(Integer blogId) {
        return userMapper.getAuthorByBlogId(blogId);
    }

    public boolean currentUserIsAuthor(Integer blogId, String token) {
       if (blogId == null || blogId < 1 || !StringUtils.hasLength(token)) {
           return false;
       }

       Integer userId =  JWTUtils.getUserIdByToken(token);
       if (userId == null || userId < 1) {
           return false;
       }

       User user = getAuthorByBlogId(blogId);
       if (user == null) {
           return false;
       }
       if (user.getId().equals(userId)) {
           return true;
       }
       return false;
    }
}
